﻿using Common.Library;
using Common.Model;
using Container.Library;
using Dapper.Library;
using DevOps.Model;
using Serialize.Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/*
* 命名空间:  DevOps.Logic
*
* 功 能：流程信息管理模块
*
* 类 名： FlowInfoServiceImpl
*
* Version   变更日期            负责人     变更内容
* ─────────────────────────────────────────────────
* V1.0.1    2021/1/15 9:42:53               Harvey     创建
*
* Copyright (c) 2020 Harvey Corporation. All rights reserved.
*/
namespace DevOps.Logic
{
    /// <summary>
    /// 流程信息管理接口实现
    /// </summary>
    public class FlowInfoServiceImpl : OperationLogicImpl, IFlowInfoService
    {
        #region 流程信息基础管理模块

        #region 查询

        /// <summary>
        /// 根据关键字 分页获取列表
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<FlowInfoResponse>> LoadPageList(ParametersInfo<string> inputInfo)
        {
            var resultInfo = new ResultJsonInfo<List<FlowInfoResponse>>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                int isDeleted = (int)FlowStatus.Deleted;
                var result = con.QuerySet<FlowInfoEntity>().Where(a => a.status != isDeleted);
                var flowType = con.QuerySet<FlowCategoryInfoEntity>().ToList();
                if (inputInfo.parameters.IsNotNullOrEmpty())
                {
                    result.Where(p => p.name.Contains(inputInfo.parameters));
                }

                #region 排序
                if (inputInfo.field.IsNullOrEmpty())
                {
                    inputInfo.field = " create_time";
                }
                if (inputInfo.order.IsNullOrEmpty())
                {
                    inputInfo.order = " desc";
                }
                if (inputInfo.order.ToLower() == "asc")
                {
                    result.OrderBy(inputInfo.field);
                }
                else
                {
                    result.OrderByDescing(inputInfo.field);
                }
                #endregion

                var queryInfo = result.PageList(inputInfo.page, inputInfo.limit);

                if (queryInfo.Items.Count > 0)
                {
                    var flowInfoList = queryInfo.Items.MapToList<FlowInfoResponse>();
                    flowInfoList.ForEach(a => a.flow_categoryname = flowType.Single(b => b.id.Equals(a.flow_category)).name);
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = flowInfoList;
                    resultInfo.Count = queryInfo.Total;
                    resultInfo.Msg = "获取成功！";
                }
                else
                {
                    resultInfo.Msg = "无对应值存在！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 根据Id值获取单条信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultJsonInfo<FlowDetailInfoResponse> LoadSingleById(string id)
        {
            var resultInfo = new ResultJsonInfo<FlowDetailInfoResponse>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                con.Transaction(tran =>
                {
                    int isDeleted = (int)FlowStatus.Deleted;
                    var result = tran.QuerySet<FlowInfoEntity>().Where(a => a.status != isDeleted && a.id.Equals(id)).Get();
                    if (result != null)
                    {

                        var detailInfo = result.MapTo<FlowDetailInfoResponse>();
                        if (result.designer_json.IsNotNullOrEmpty())
                        {
                            var designerJson = result.designer_json.JsonToObject<FlowDetailInfoRequest>();
                            detailInfo.nodeList = designerJson.nodeList;
                            detailInfo.lineList = designerJson.lineList;
                        }
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Data = detailInfo;
                        resultInfo.Msg = "获取成功！";
                    }
                    else
                    {
                        resultInfo.Msg = "无对应值存在！";
                    }
                });
            }
            return resultInfo;
        }

        /// <summary>
        /// 获取所有用户机构树状信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<DepartmentUserTreeInfo>> LoadDepartmentUserTreeList()
        {
            var resultInfo = new ResultJsonInfo<List<DepartmentUserTreeInfo>>();
            List<DepartmentUserTreeInfo> listInfo = new List<DepartmentUserTreeInfo>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var departmentList = con.QuerySet<SysDepartmentInfoEntity>()
                            .Where(p => p.is_deleted == false).OrderBy(p => p.sort)
                            .ToList();
                var departmentInfos = departmentList.MapToList<DepartmentTreeResponse>();

                var userInfo = con.QuerySet<View_SysUserEntity>().OrderBy(a => a.sort).ToList();
                var userInfos = userInfo.MapToList<UserTreeInfoResponse>();
                int index = 1;
                foreach (var item in departmentInfos)
                {
                    item.id = ++index;
                }
                foreach (var item in userInfos)
                {
                    item.id = ++index;
                }
                if (departmentInfos.Count > 0)
                {
                    List<int> usedIdList = new List<int>();
                    var departmentInfo = new DepartmentUserTreeInfo()
                    {
                        id = 1,
                        label = "公司组织信息",
                        pid = 0,
                        type = 100,
                        key = "",
                        children = GetDepartmentUserTree(departmentInfos, "", userInfos, usedIdList)
                    };
                    listInfo.Add(departmentInfo);
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo;
                    resultInfo.Msg = "获取成功！";
                }
                else
                {
                    resultInfo.Msg = "获取组织机构树状失败！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 获取流程处理者类型
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<EnumToSelectItem>> LoadFlowHandlerTypeList()
        {

            var resultInfo = new ResultJsonInfo<List<EnumToSelectItem>>();
            resultInfo.Data = EnumToSelectItem.GetEnumDescriptionList(typeof(FlowHandlerType), true);
            resultInfo.Code = ActionCodes.Success;
            resultInfo.Msg = "获取成功！";
            return resultInfo;
        }

        /// <summary>
        /// 获取流程退回类型
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<EnumToSelectItem>> LoadFlowReturnTypeList()
        {
            var resultInfo = new ResultJsonInfo<List<EnumToSelectItem>>();
            resultInfo.Data = EnumToSelectItem.GetEnumDescriptionList(typeof(FlowReturnType), true);
            resultInfo.Code = ActionCodes.Success;
            resultInfo.Msg = "获取成功！";
            return resultInfo;
        }

        /// <summary>
        /// 获取流程处理策略
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<EnumToSelectItem>> LoadFlowHandleStrategyList()
        {
            var resultInfo = new ResultJsonInfo<List<EnumToSelectItem>>();
            resultInfo.Data = EnumToSelectItem.GetEnumDescriptionList(typeof(FlowHandleStrategy), true);
            resultInfo.Code = ActionCodes.Success;
            resultInfo.Msg = "获取成功！";
            return resultInfo;
        }


        /// <summary>
        /// 获取会签策略
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<EnumToSelectItem>> LoadFlowSignStrategyList()
        {

            var resultInfo = new ResultJsonInfo<List<EnumToSelectItem>>();
            resultInfo.Data = EnumToSelectItem.GetEnumDescriptionList(typeof(FlowSignStrategy), true);
            resultInfo.Code = ActionCodes.Success;
            resultInfo.Msg = "获取成功！";
            return resultInfo;
        }

        #endregion

        #region 更新

        /// <summary>
        /// 编辑流程
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> Save(FlowInfoRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            var user = GetLoginUserInfo();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {

                con.Transaction(tran =>
                {
                    //修改
                    if (inputInfo.id.IsNotNullOrEmpty())
                    {
                        #region 修改
                        var info = tran.QuerySet<FlowInfoEntity>().Where(p => p.id.Equals(inputInfo.id)).Get();
                        if (info != null)
                        {
                            info.name = inputInfo.name;
                            info.flow_category = inputInfo.flow_category;
                            info.remarks = inputInfo.remarks;
                            info.manager = inputInfo.manager;
                            info.managername = inputInfo.managername;
                            info.form_key = inputInfo.form_key;
                            info.sort = inputInfo.sort;
                            var result = tran.CommandSet<FlowInfoEntity>().Update(info);
                            if (result > 0)
                            {

                                resultInfo.Code = ActionCodes.Success;
                                resultInfo.Msg = "修改成功！";

                                AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.ProcessManagement, $"修改流程信息，修改信息：{JsonHelper.ToJson(inputInfo)}");
                            }
                            else
                            {
                                resultInfo.Code = ActionCodes.InvalidOperation;
                                resultInfo.Msg = "修改失败！";
                            }
                        }
                        else
                        {
                            resultInfo.Code = ActionCodes.InvalidOperation;
                            resultInfo.Msg = "Id无对应信息！";
                        }
                        #endregion
                    }
                    else
                    {
                        #region 新增
                        var pjInfo = inputInfo.MapTo<FlowInfoEntity>();
                        pjInfo.id = GuidHelper.GetGuid();
                        pjInfo.create_time = DateTime.Now;
                        pjInfo.create_user = user.id;
                        pjInfo.create_user_name = user.realname;
                        pjInfo.status = (int)FlowStatus.UnderDesign;
                        pjInfo.sort = inputInfo.sort;
                        var result = tran.CommandSet<FlowInfoEntity>().Insert(pjInfo);

                        if (result > 0)
                        {
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Msg = "添加成功！";

                            AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.ProcessManagement, $"新增流程信息，新增信息：{JsonHelper.ToJson(inputInfo)}");
                        }
                        else
                        {
                            resultInfo.Code = ActionCodes.InvalidOperation;
                            resultInfo.Msg = "修改失败！";
                        }
                        #endregion
                    }
                });
            }
            return resultInfo;
        }

        /// <summary>
        /// 编辑流程
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> SaveFlowMapl(FlowDetailInfoRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {

                con.Transaction(tran =>
                {
                    //修改
                    if (inputInfo.id.IsNotNullOrEmpty())
                    {
                        #region 修改
                        var info = tran.QuerySet<FlowInfoEntity>().Where(p => p.id.Equals(inputInfo.id)).Get();
                        if (info != null)
                        {

                            //步骤表信息
                            if (inputInfo.nodeList.Count > 0)
                            {
                                foreach (var item in inputInfo.nodeList)
                                {
                                    if (!item.id.IsNotNullOrEmpty())
                                    {
                                        item.id = GuidHelper.GetGuid();
                                    }
                                    item.flow_id = inputInfo.id;
                                    item.flow_name = inputInfo.name;
                                    var parentInfo = inputInfo.lineList.Find(p => p.to.Equals(item.id));
                                    if (parentInfo != null)
                                    {
                                        item.parent_id = parentInfo.from;
                                    }
                                }
                            }
                            //连线表信息
                            if (inputInfo.lineList.Count > 0)
                            {
                                foreach (var item in inputInfo.lineList)
                                {
                                    item.id = GuidHelper.GetGuid();
                                    item.flow_id = inputInfo.id;
                                    item.flow_name = inputInfo.name;
                                }
                            }
                            info.designer_json = inputInfo.ToJson();
                            var result = tran.CommandSet<FlowInfoEntity>().Update(info);
                            if (result > 0)
                            {
                                resultInfo.Code = ActionCodes.Success;
                                resultInfo.Msg = "修改成功！";
                                AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.ProcessManagement, $"修改流程图信息，修改信息：{JsonHelper.ToJson(inputInfo)}");
                            }
                            else
                            {
                                resultInfo.Code = ActionCodes.InvalidOperation;
                                resultInfo.Msg = "修改失败！";
                            }
                        }
                        else
                        {
                            resultInfo.Code = ActionCodes.InvalidOperation;
                            resultInfo.Msg = "Id无对应信息！";
                        }
                        #endregion
                    }
                });
            }
            return resultInfo;
        }

        /// <summary>
        /// 安装流程
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> InstallFlowMapl(FlowDetailInfoRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                con.Transaction(tran =>
                {
                    //修改
                    if (inputInfo.id.IsNotNullOrEmpty())
                    {
                        var info = tran.QuerySet<FlowInfoEntity>().Where(p => p.id.Equals(inputInfo.id)).Get();
                        if (info != null)
                        {
                            //步骤表信息
                            if (inputInfo.nodeList.Count > 0)
                            {
                                foreach (var item in inputInfo.nodeList)
                                {
                                    if (!item.id.IsNotNullOrEmpty())
                                    {
                                        item.id = GuidHelper.GetGuid();
                                    }
                                    item.flow_id = inputInfo.id;
                                    item.flow_name = inputInfo.name;
                                    var parentInfo = inputInfo.lineList.Find(p => p.to.Equals(item.id));
                                    if (parentInfo != null)
                                    {
                                        item.parent_id = parentInfo.from;
                                    }
                                }
                            }
                            //连线表信息
                            if (inputInfo.lineList.Count > 0)
                            {
                                foreach (var item in inputInfo.lineList)
                                {
                                    item.id = GuidHelper.GetGuid();
                                    item.flow_id = inputInfo.id;
                                    item.flow_name = inputInfo.name;
                                }
                            }

                            info.designer_json = inputInfo.ToJson();
                            info.status = (int)FlowStatus.Installed;

                            var result = tran.CommandSet<FlowInfoEntity>().Update(info);
                            if (result > 0)
                            {
                                //先删除步骤表信息
                                tran.CommandSet<FlowStepInfoEntity>().Where(p => p.flow_id == inputInfo.id).Delete();
                                //插入步骤表信息
                                if (inputInfo.nodeList.Count > 0)
                                {
                                    tran.CommandSet<FlowStepInfoEntity>().Insert(inputInfo.nodeList);
                                }

                                //先删除连线表信息
                                tran.CommandSet<FlowLineInfoEntity>().Where(p => p.flow_id == inputInfo.id).Delete();
                                if (inputInfo.lineList.Count > 0)
                                {
                                    tran.CommandSet<FlowLineInfoEntity>().Insert(inputInfo.lineList);
                                }

                                resultInfo.Code = ActionCodes.Success;
                                resultInfo.Msg = "安装成功！";
                                AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.ProcessManagement, $"安装流程图信息，安装信息：{JsonHelper.ToJson(inputInfo)}");
                            }
                            else
                            {
                                resultInfo.Code = ActionCodes.InvalidOperation;
                                resultInfo.Msg = "修改失败！";
                            }
                        }
                        else
                        {
                            resultInfo.Code = ActionCodes.InvalidOperation;
                            resultInfo.Msg = "Id无对应信息！";
                        }
                    }
                });
            }
            return resultInfo;
        }

        /// <summary>
        /// 单独实现【安装/卸载】
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> InstallUninstall(string id)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var user = GetLoginUserInfo();
                con.Transaction(tran =>
                {
                    var info = tran.QuerySet<FlowInfoEntity>().Where(a => a.id.Equals(id)).Get();
                    switch (info.status)
                    {
                        case (int)FlowStatus.UnderDesign:
                        case (int)FlowStatus.Unloaded:
                            info.status = (int)FlowStatus.Installed;
                            info.install_time = DateTime.Now;
                            info.install_user = user.id;
                            info.install_user_name = user.realname;
                            break;
                        case (int)FlowStatus.Installed:
                            info.status = (int)FlowStatus.Unloaded;
                            break;
                    }
                    var result = tran.CommandSet<FlowInfoEntity>().Update(info);
                    if (result > 0)
                    {
                        //如果是安装，那就需要更改步骤表和连线表
                        if (info.status == (int)FlowStatus.Installed)
                        {
                            if (info.designer_json.IsNotNullOrEmpty())
                            {
                                var flowdetailInfo = info.designer_json.JsonToObject<FlowDetailInfoRequest>();
                                //先删除步骤表信息
                                tran.CommandSet<FlowStepInfoEntity>().Where(p => p.flow_id == info.id).Delete();
                                //插入步骤表信息
                                if (flowdetailInfo.nodeList.Count > 0)
                                {
                                    tran.CommandSet<FlowStepInfoEntity>().Insert(flowdetailInfo.nodeList);
                                }
                                //先删除连线表信息
                                tran.CommandSet<FlowLineInfoEntity>().Where(p => p.flow_id == info.id).Delete();
                                if (flowdetailInfo.lineList.Count > 0)
                                {
                                    tran.CommandSet<FlowLineInfoEntity>().Insert(flowdetailInfo.lineList);
                                }

                                resultInfo.Msg = "安装成功！";
                                resultInfo.Code = ActionCodes.Success;
                                AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.ProcessManagement, $"安装流程信息!{JsonHelper.ToJson(id)}");
                            }
                            else
                            {
                                resultInfo.Msg = "无流程图信息，无法安装！";
                            }
                        }
                        else
                        {
                            //先删除步骤表信息
                            tran.CommandSet<FlowStepInfoEntity>().Where(p => p.flow_id == info.id).Delete();
                            //先删除连线表信息
                            tran.CommandSet<FlowLineInfoEntity>().Where(p => p.flow_id == info.id).Delete();

                            resultInfo.Msg = "卸载成功！";
                            resultInfo.Code = ActionCodes.Success;
                            AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.ProcessManagement, $"卸载流程信息!{JsonHelper.ToJson(id)}");
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "处理失败！";
                    }
                });
            }
            return resultInfo;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> ids)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                con.Transaction(tran =>
                {
                    //删除
                    var info = tran.QuerySet<FlowInfoEntity>().Where(p => p.id.In(ids.ToArray())).ToList();
                    info.ForEach(a => a.status = (int)FlowStatus.Deleted);

                    var result = tran.CommandSet<FlowInfoEntity>().Update(info);
                    if (result > 0)
                    {
                        foreach (var item in info)
                        {
                            //先删除步骤表信息
                            tran.CommandSet<FlowStepInfoEntity>().Where(p => p.flow_id == item.id).Delete();
                            //先删除连线表信息
                            tran.CommandSet<FlowLineInfoEntity>().Where(p => p.flow_id == item.id).Delete();
                        }
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "删除成功！";
                        AddOperationLog(OperationLogType.RemoveOperation, BusinessTitleType.ProcessManagement, $"删除流程信息!{JsonHelper.ToJson(ids)}");
                    }
                    else
                    {
                        resultInfo.Msg = "删除失败！";
                    }
                });

            }
            return resultInfo;
        }
        #endregion

        #endregion

        #region 流程过程操作逻辑

        /// <summary>
        /// 获取起始步骤的后一步的步骤【这一步主要找出步骤中，可以参与审批的人员】
        /// </summary>
        /// <param name="flowKey">流程ID在参数表中的Key</param>
        /// <returns></returns>
        public ResultJsonInfo<FlowStepCurrentInfo> LoadBeginNextStepInfo(string flowKey)
        {
            var resultInfo = new ResultJsonInfo<FlowStepCurrentInfo>();

            var user = GetLoginUserInfo();
           

            var currentInfo = new FlowStepCurrentInfo();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                con.Transaction(tran =>
                {
                    string flowId = tran.QuerySet<FlowInfoEntity>().Where(p => p.form_key.Equals(flowKey)&&p.status==110).Get().id;

                    int stepType = (int)FlowStepType.Initialized;
                    //1、查询起始步骤
                    var startStep = tran.QuerySet<FlowStepInfoEntity>().Where(p => p.flow_id.Equals(flowId) && p.type == stepType).Get();
                    if (startStep != null)
                    {
                        currentInfo.currentStep = startStep.MapTo<FlowStepInfoOperation>();
                        //获取当前步骤按钮
                        var buttonIds = startStep.button_ids.Split(',');
                        var buttonInfos = tran.QuerySet<FlowButtonInfoEntity>().Where(p => p.id.In(buttonIds)).ToList();
                        currentInfo.currentStep.button_json = buttonInfos.ToJson();

                        //获取下一步骤的信息
                        var lines = tran.QuerySet<FlowLineInfoEntity>().Where(p => p.from.Equals(startStep.id)).ToList(p => p.to).ToArray();
                        var nextSteps = tran.QuerySet<FlowStepInfoEntity>().Where(p => p.id.In(lines)).ToList();
                        var nextStepList = nextSteps.MapToList<FlowStepInfoOperation>();

                        foreach (var item in nextStepList)
                        {
                            if (item.is_choosable == (int)FlowStepChooseType.Choosable)
                            {
                                //判断操作人员类型
                                switch (item.handler_type)
                                {
                                    case (int)FlowHandlerType.AllPersonnel:
                                        //所有人员的情况下，choose_person为空
                                        item.choose_person = "all";
                                        break;
                                    case (int)FlowHandlerType.SelectPersonnel:
                                        //选中人员的情况下，choose_person为已经选择了的
                                        break;
                                    case (int)FlowHandlerType.DepartmentHead://发起者部门领导
                                    case (int)FlowHandlerType.SuperiorHead://发起者上级部门领导
                                    case (int)FlowHandlerType.AllHead://发起者所有上级部门领导
                                        var leaders = GetDepartmentLeader(user, item.handler_type);
                                        if (leaders.Count > 0)
                                        {
                                            item.choose_person = string.Join(",", leaders.Select(p => p.id).ToArray());
                                            item.person_name = string.Join(",", leaders.Select(p => p.realname).ToArray());

                                            item.default_handler = leaders[0].id;
                                            item.handler_name = leaders[0].realname;
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                            if (item.default_handler.IsNullOrEmpty())
                            {
                                item.default_handler = item.choose_person.Split(',')[0];
                                item.handler_name = item.person_name.Split(',')[0];
                            }
                        }
                        currentInfo.nextSteps = nextStepList;
                        resultInfo.Msg = "操作成功";
                        resultInfo.Data = currentInfo;
                        resultInfo.Code = ActionCodes.Success;
                    }
                    else
                    {
                        resultInfo.Msg = "无对应流程步骤";
                    }
                });
            }
            return resultInfo;
        }

        /// <summary>
        /// 根据步骤Id获取后一步的步骤
        /// </summary>
        /// <param name="stepId">步骤Id</param>
        /// <returns></returns>
        public ResultJsonInfo<FlowStepCurrentInfo> LoadNextStepInfo(string stepId)
        {

            var resultInfo = new ResultJsonInfo<FlowStepCurrentInfo>();
            var user = GetLoginUserInfo();
            var currentInfo = new FlowStepCurrentInfo();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                con.Transaction(tran =>
                {
                    //1、查询对应步骤信息
                    var stepInfo = tran.QuerySet<FlowStepInfoEntity>().Where(p => p.id.Equals(stepId)).Get();
                    if (stepInfo != null)
                    {
                        currentInfo.currentStep = stepInfo.MapTo<FlowStepInfoOperation>();
                        //获取当前步骤按钮
                        var buttonIds = stepInfo.button_ids.Split(',');
                        var buttonInfos = tran.QuerySet<FlowButtonInfoEntity>().Where(p => p.id.In(buttonIds)).ToList();
                        currentInfo.currentStep.button_json = buttonInfos.ToJson();

                        //获取下一步骤的信息
                        var lines = tran.QuerySet<FlowLineInfoEntity>().Where(p => p.from.Equals(stepInfo.id)).ToList(p => p.to).ToArray();
                        var nextSteps = tran.QuerySet<FlowStepInfoEntity>().Where(p => p.id.In(lines)).ToList();
                        var nextStepList = nextSteps.MapToList<FlowStepInfoOperation>();

                        foreach (var item in nextStepList)
                        {
                            if (item.is_choosable == (int)FlowStepChooseType.Choosable)
                            {
                                //判断操作人员类型
                                switch (item.handler_type)
                                {
                                    case (int)FlowHandlerType.AllPersonnel:
                                        //所有人员的情况下，choose_person为空
                                        item.choose_person = "all";
                                        break;
                                    case (int)FlowHandlerType.SelectPersonnel:
                                        //选中人员的情况下，choose_person为已经选择了的
                                        break;
                                    case (int)FlowHandlerType.DepartmentHead://发起者部门领导
                                    case (int)FlowHandlerType.SuperiorHead://发起者上级部门领导
                                    case (int)FlowHandlerType.AllHead://发起者所有上级部门领导
                                        var leaders = GetDepartmentLeader(user, item.handler_type);
                                        if (leaders.Count > 0)
                                        {
                                            item.choose_person = string.Join(",", leaders.Select(p => p.id).ToArray());
                                            item.person_name = string.Join(",", leaders.Select(p => p.realname).ToArray());

                                            item.default_handler = leaders[0].id;
                                            item.handler_name = leaders[0].realname;
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }

                            if (item.default_handler.IsNullOrEmpty())
                            {
                                item.default_handler = item.choose_person.Split(',')[0];
                                item.handler_name = item.person_name.Split(',')[0];
                            }
                        }

                        currentInfo.nextSteps = nextStepList;
                        resultInfo.Msg = "操作成功";
                        resultInfo.Data = currentInfo;
                        resultInfo.Code = ActionCodes.Success;
                    }
                    else
                    {
                        resultInfo.Msg = "无对应流程步骤";
                    }
                });
            }
            return resultInfo;
        }

        /// <summary>
        /// 发起流程
        /// </summary>
        /// <param name="inputInfo ">instance_id业务主键 currentFlowInput 当前步骤和下个步骤的信息</param>
        /// <returns></returns>
        public ResultJsonInfo<bool> InitiateFlow(FlowInitiateRequest inputInfo)
        {

            var resultInfo = new ResultJsonInfo<bool>();
            var user = GetLoginUserInfo();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                con.Transaction(tran =>
                {
                    var flowId = inputInfo.currentFlowInput.currentStep.flow_id;
                    //1、查询起始步骤
                    var flowStepInfos = tran.QuerySet<FlowStepInfoEntity>().Where(p => p.flow_id.Equals(flowId)).ToList();
                    if (flowStepInfos.Count > 0)
                    {

                        List<FlowTaskInfoEntity> flowTaskInfos = new List<FlowTaskInfoEntity>();
                        //获取起始步骤
                        var startStep = flowStepInfos.Find(p => p.parent_id == "");
                        //流程第一步任务
                        int waitingStatus = (int)FlowTaskStatus.Waiting;
                        var flowTaskInfo = tran.QuerySet<FlowTaskInfoEntity>().Where(p => p.instance_id.Equals(inputInfo.instance_id)&&p.status== waitingStatus).Get();

                        if (flowTaskInfo != null){
                            flowTaskInfo.task_type = (int)FlowTaskType.General;
                            flowTaskInfo.status = (int)FlowTaskStatus.Completed;
                            flowTaskInfo.finish_time = DateTime.Now;
                            flowTaskInfo.execute_type = (int)FlowTaskExecuteType.Completed;
                            tran.CommandSet<FlowTaskInfoEntity>().Update(flowTaskInfo);
                        }
                        else{
                            //1、生成起始任务
                            #region 发起人操作信息--第一个自己发给自己
                            flowTaskInfo = new FlowTaskInfoEntity();
                            flowTaskInfo.id = GuidHelper.GetGuid();
                            flowTaskInfo.parent_id = "";
                            flowTaskInfo.flow_id = inputInfo.currentFlowInput.currentStep.flow_id;
                            flowTaskInfo.flow_name = startStep.flow_name;
                            flowTaskInfo.step_id = startStep.id;
                            flowTaskInfo.step_name = startStep.name;
                            flowTaskInfo.instance_id = inputInfo.instance_id;
                            flowTaskInfo.task_type = (int)FlowTaskType.General;
                            flowTaskInfo.title = startStep.flow_name + "-" + startStep.name;
                            flowTaskInfo.sender_id = user.id;
                            flowTaskInfo.sender_name = user.realname;
                            flowTaskInfo.receive_id = user.id;
                            flowTaskInfo.receive_name = user.realname;
                            flowTaskInfo.receive_time = DateTime.Now;
                            flowTaskInfo.finish_time = DateTime.Now;
                            flowTaskInfo.status = (int)FlowTaskStatus.Completed;
                            flowTaskInfo.sort = 0;
                            flowTaskInfo.execute_type = (int)FlowTaskExecuteType.Completed;
                            flowTaskInfos.Add(flowTaskInfo);
                            #endregion
                        }

                        #region 发起人派发给用户
                        var nextSteps = inputInfo.currentFlowInput.nextSteps;
                        int sortIndex = 1;//任务顺序
                        //下一步流程，有几个分子
                        if (nextSteps.Count > 0)
                        {
                            foreach (var item in nextSteps)
                            {
                                //每个分子有几个人
                                var examinePersons = item.examine_person.Split(',');
                                var examineNames = item.examine_name.Split(',');
                                int index = 0;
                                FlowTaskInfoEntity flowTaskInfoNext = null;
                                foreach (var itemPerson in examinePersons)
                                {
                                    flowTaskInfoNext = new FlowTaskInfoEntity();
                                    flowTaskInfoNext.id = GuidHelper.GetGuid();
                                    flowTaskInfoNext.parent_id = flowTaskInfo.id;
                                    flowTaskInfoNext.parent_step_id = startStep.id;
                                    flowTaskInfoNext.flow_id = flowId;
                                    flowTaskInfoNext.flow_name = item.flow_name;
                                    flowTaskInfoNext.step_id = item.id;
                                    flowTaskInfoNext.step_name = item.name;
                                    flowTaskInfoNext.instance_id = inputInfo.instance_id;
                                    flowTaskInfoNext.task_type = (int)FlowTaskType.General;
                                    flowTaskInfoNext.title = startStep.flow_name + "-" + item.name;
                                    flowTaskInfoNext.sender_id = user.id;
                                    flowTaskInfoNext.sender_name = user.realname;
                                    flowTaskInfoNext.receive_id = itemPerson;
                                    flowTaskInfoNext.receive_name = examineNames[index++];
                                    flowTaskInfoNext.receive_time = DateTime.Now;
                                    flowTaskInfoNext.finish_time = null;
                                    flowTaskInfoNext.status = (int)FlowTaskStatus.Waiting;
                                    flowTaskInfoNext.sort = sortIndex++;
                                    flowTaskInfoNext.execute_type = (int)FlowTaskExecuteType.Waiting;
                                    flowTaskInfos.Add(flowTaskInfoNext);
                                }
                            }
                        }
                        #endregion

                        var result = tran.CommandSet<FlowTaskInfoEntity>().Insert(flowTaskInfos);
                        if (result > 0)
                        {
                            resultInfo.Msg = "操作成功";
                            resultInfo.Code = ActionCodes.Success;
                        }
                        else
                        {
                            resultInfo.Msg = "流程发起失败";
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "无对应流程步骤";
                    }
                });
            }
            return resultInfo;
        }


        #region 发送/同意/完成流程

        /// <summary>
        ///发送/同意流程
        /// </summary>
        /// <param name="inputInfo ">instance_id业务主键 currentFlowInput 当前步骤和下个步骤的信息</param>
        /// <returns></returns>
        public ResultJsonInfo<bool> AgreeFlow(FlowAgreeRequest inputInfo)
        {

            var resultInfo = new ResultJsonInfo<bool>();
            var user = GetLoginUserInfo();

            //当前任务的信息
            var taskInfo = new FlowTaskInfoEntity();

            #region 先把当前任务的状态改了
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                //当前任务的信息
                taskInfo = con.QuerySet<FlowTaskInfoEntity>().Where(p => p.id.Equals(inputInfo.taskId)).Get();
                taskInfo.comments = inputInfo.comments;
                taskInfo.finish_time = DateTime.Now;
                taskInfo.status = (int)FlowTaskStatus.Completed;
                taskInfo.execute_type = (int)FlowTaskExecuteType.Completed;
                con.CommandSet<FlowTaskInfoEntity>().Update(taskInfo);

                //该实例对应的所有任务
                int isReturned = (int)FlowTaskExecuteType.Returned;
                var allTasks = con.QuerySet<FlowTaskInfoEntity>().Where(p => p.instance_id.Equals(taskInfo.instance_id)&&p.execute_type!= isReturned).ToList();
                //该流程对应的所有步骤
                var allSteps = con.QuerySet<FlowStepInfoEntity>().Where(p => p.flow_id.Equals(taskInfo.flow_id)).ToList();
                //当前步骤
                var nowStep = allSteps.Find(p => p.id.Equals(inputInfo.currentFlowInput.currentStep.id));
                //当前任务【同一步骤的】任务的信息
                var sameStepTaskInfos = allTasks.Where(p => p.instance_id.Equals(taskInfo.instance_id) && p.step_id.Equals(taskInfo.step_id)).ToList();
                var goNext = JudgmentStepCanBeNext(nowStep, sameStepTaskInfos);
                #region 判断当前步骤任务能否进入下一步,如果可以，先把状态改了
                if (goNext)
                {
                    foreach (var item in sameStepTaskInfos)
                    {
                        item.finish_time = DateTime.Now;
                        item.status = (int)FlowTaskStatus.Completed;
                        item.execute_type = (int)FlowTaskExecuteType.Completed;
                    }
                    con.CommandSet<FlowTaskInfoEntity>().Update(sameStepTaskInfos);
                }
                #endregion

            }
            #endregion

            //再来操作其余逻辑
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                con.Transaction(tran =>
                {
                    //获取该任务对应的步骤信息。
                    var currentStep = inputInfo.currentFlowInput.currentStep;

                    //该实例对应的所有任务
                    int isReturned = (int)FlowTaskExecuteType.Returned;
                    var allTasks = tran.QuerySet<FlowTaskInfoEntity>().Where(p => p.instance_id.Equals(taskInfo.instance_id) && p.execute_type != isReturned).ToList();
                    //该流程对应的所有步骤
                    var allSteps = tran.QuerySet<FlowStepInfoEntity>().Where(p => p.flow_id.Equals(taskInfo.flow_id)).ToList();
                    //该流程对应的所有连线
                    var allStepIds = allSteps.Select(p => p.id).ToArray();
                    var allLines = tran.QuerySet<FlowLineInfoEntity>().Where(p => p.from.In(allStepIds) || p.to.In(allStepIds)).ToList();

                    //当前步骤
                    var nowStep = allSteps.Find(p => p.id.Equals(currentStep.id));

                    ///////////////会签要用到///////////////会签要用到///////////////会签要用到///////////////会签要用到///////////////会签要用到///////////////////
                    //获取该任务对应的步骤同级所有步骤
                    var lines = allLines.Where(p => p.from.Equals(currentStep.id)).Select(p => p.to).ToArray();
                    //获取该任务对应的步骤同级所有步骤Ids
                    var currentSiblingStepIds = allLines.Where(p => lines.Contains(p.to)).Select(p => p.from).ToArray();
                    //获取该任务对应的步骤同级所有步骤
                    var currentSiblingSteps = allSteps.Where(p => currentSiblingStepIds.Contains(p.id)).ToList();
                    //当前任务对应同级所有步骤的所有任务
                    var currentSiblingStepTasks = allTasks.FindAll(p => currentSiblingStepIds.Contains(p.step_id)).ToList();
                    //当前任务【同级步骤的下发的】任务的信息
                    var currentSiblingStepNextTaskInfos = allTasks.Where(p => p.instance_id.Equals(taskInfo.instance_id) && currentSiblingStepIds.Contains(p.parent_step_id)).ToList();

                    #region 会签策略逻辑

                    bool goNext = true;

                    //先看会签策略，再看步骤内部策略
                    switch (currentStep.sign_strategy)
                    {
                        //如果不会签，只需要将任务状态设置成待处理，保持任务接收人是唯一的
                        case (int)FlowSignStrategy.NotSign:
                            break;
                        //如果所有步骤都要同意
                        case (int)FlowSignStrategy.AllStepsAgree:
                            //1、判断其他的步骤是否同意
                            foreach (var item in currentSiblingSteps)
                            {
                                var assignStepTasks = allTasks.FindAll(p => p.step_id == item.id).ToList();
                                var canBeNext = JudgmentStepCanBeNext(item, assignStepTasks);
                                if (!canBeNext)
                                {
                                    goNext = false;
                                }
                            }
                            break;
                        case (int)FlowSignStrategy.OneStepAgree:
                            //1、判断其他的步骤是否同意
                            foreach (var item in currentSiblingSteps)
                            {
                                var assignStepTasks = allTasks.FindAll(p => p.step_id == item.id).ToList();
                                var canBeNext = JudgmentStepCanBeNext(item, assignStepTasks);
                                if (canBeNext)
                                {
                                    goNext = true;
                                }
                            }
                            break;
                        case (int)FlowSignStrategy.Wahlbeteiligung:
                            int agreeNum = 0;
                            //1、判断其他的步骤是否同意
                            foreach (var item in currentSiblingSteps)
                            {
                                var assignStepTasks = allTasks.FindAll(p => p.step_id == item.id).ToList();
                                var canBeNext = JudgmentStepCanBeNext(item, assignStepTasks);
                                if (canBeNext)
                                {
                                    agreeNum++;
                                }
                            }
                            if (agreeNum/double.Parse(currentSiblingSteps.Count.ToString())>=nowStep.sign_percent)
                            {
                                goNext = true;
                            }
                            else
                            {
                                goNext = false;
                            }
                            break;
                    }
                    #region 派发任务给用户   
                    if (goNext)
                    {
                        //登录用户信息
                        //当前任务的信息
                        //当前节点和后续节点信息
                        //当前任务对应【同级所有步骤的】所有任务的信息
                        //当前任务【同级步骤的下发的】任务的信息
                        var flowTaskInfos = GetNewFlowTaskInfos(goNext, user, taskInfo, inputInfo, currentSiblingStepTasks, currentSiblingStepNextTaskInfos);
                        if (flowTaskInfos.Count>0)
                        {
                            tran.CommandSet<FlowTaskInfoEntity>().Insert(flowTaskInfos);
                        }

                        //当前任务【同一步骤的下发的】任务的信息的状态修改
                        if (currentSiblingStepNextTaskInfos.Count>0)
                        {
                            foreach (var item in currentSiblingStepNextTaskInfos)
                            {
                                item.status = (int)FlowTaskStatus.Waiting;
                                item.execute_type = (int)FlowTaskExecuteType.Waiting;
                                item.finish_time = DateTime.Now;
                            }
                            tran.CommandSet<FlowTaskInfoEntity>().Update(currentSiblingStepNextTaskInfos);
                        }
                    }
                    else
                    {
                        //登录用户信息
                        //当前任务的信息
                        //当前节点和后续节点信息
                        //当前任务对应【同级所有步骤的】所有任务的信息
                        //当前任务【同级步骤的下发的】任务的信息
                        var flowTaskInfos = GetNewFlowTaskInfos(goNext, user, taskInfo, inputInfo, currentSiblingStepTasks, currentSiblingStepNextTaskInfos);
                        if (flowTaskInfos.Count > 0)
                        {
                            tran.CommandSet<FlowTaskInfoEntity>().Insert(flowTaskInfos);
                        }
                    }
                    #endregion
                    #endregion

                    resultInfo.Msg = "操作成功";
                    resultInfo.Code = ActionCodes.Success;
                });
            }
            return resultInfo;
        }

        /// <summary>
        /// 判断任务能否进入下一步
        /// </summary>
        /// <param name="stepInfo">步骤信息</param>
        /// <param name="taskInfos">该步骤对应的所有任务信息</param>
        private bool JudgmentStepCanBeNext(FlowStepInfoEntity stepInfo, List<FlowTaskInfoEntity> taskInfos)
        {
            bool result = false;
            var completedCount = taskInfos.Count(p => p.status == (int)FlowTaskStatus.Completed);
            switch (stepInfo.processing_strategy)
            {
                //所有人必须同意
                case (int)FlowHandleStrategy.EveryoneHasAgree:
                    #region 所有人必须同意
                    //1、如果全部同意，就可以进入下一步
                    if (completedCount == taskInfos.Count)
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;
                    }
                    #endregion
                    break;
                case (int)FlowHandleStrategy.JustOneAgree:
                    if (completedCount>0)
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;
                    }
                    break;
                case (int)FlowHandleStrategy.Wahlbeteiligung:
                    double processingPercent = completedCount / double.Parse(taskInfos.Count.ToString());
                    if (processingPercent >= stepInfo.processing_percent)
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;
                    }
                    break;
            }
            return result;
        }

        /// <summary>
        /// 获取新增任务节点信息
        /// </summary>
        /// <param name="goNext">是否下发任务</param>
        /// <param name="userInfo">登录用户信息</param>
        /// <param name="taskInfo">当前任务的信息</param>
        /// <param name="inputInfo">当前节点和后续节点信息</param>
        /// <param name="sameStepTaskInfos">当前任务【同一步骤的】任务的信息</param>
        /// <param name="sameStepNextTaskInfos">当前任务【同一步骤的下发的】任务的信息</param>
        /// <returns></returns>
        private List<FlowTaskInfoEntity> GetNewFlowTaskInfos(bool goNext,UserLoginInfo userInfo,
                                                            FlowTaskInfoEntity taskInfo,
                                                            FlowAgreeRequest inputInfo, 
                                                            List<FlowTaskInfoEntity> sameStepTaskInfos, 
                                                            List<FlowTaskInfoEntity> sameStepNextTaskInfos) {

            List<FlowTaskInfoEntity> flowTaskInfos = new List<FlowTaskInfoEntity>();
            int sortIndex = sameStepTaskInfos.Max(p => p.sort) + sameStepNextTaskInfos.Count + 1;//任务顺序
            var nextSteps = inputInfo.currentFlowInput.nextSteps;
            if (nextSteps.Count > 0)
            {
                foreach (var item in nextSteps)
                {
                    //每个分子有几个人
                    var examinePersons = item.examine_person.Split(',');
                    var examineNames = item.examine_name.Split(',');
                    int index = 0;
                    FlowTaskInfoEntity flowTaskInfoNext = null;
                    foreach (var itemPerson in examinePersons)
                    {
                        //如果不存在，就增加
                        if (!sameStepNextTaskInfos.Exists(p => p.receive_id == itemPerson))
                        {
                            flowTaskInfoNext = new FlowTaskInfoEntity();
                            flowTaskInfoNext.id = GuidHelper.GetGuid();
                            flowTaskInfoNext.parent_id = taskInfo.id;
                            flowTaskInfoNext.flow_id = item.flow_id;
                            flowTaskInfoNext.flow_name = item.flow_name;
                            flowTaskInfoNext.step_id = item.id;
                            flowTaskInfoNext.parent_step_id = taskInfo.step_id;
                            flowTaskInfoNext.step_name = item.name;
                            flowTaskInfoNext.instance_id = taskInfo.instance_id;
                            flowTaskInfoNext.task_type = (int)FlowTaskType.General;
                            flowTaskInfoNext.title = taskInfo.flow_name + "-" + item.name;
                            flowTaskInfoNext.sender_id = userInfo.id;
                            flowTaskInfoNext.sender_name = userInfo.realname;
                            flowTaskInfoNext.receive_id = itemPerson;
                            flowTaskInfoNext.receive_name = examineNames[index++];
                            flowTaskInfoNext.receive_time = DateTime.Now;
                            if (goNext)
                            {
                                flowTaskInfoNext.finish_time = DateTime.Now;
                                flowTaskInfoNext.status = (int)FlowTaskStatus.Waiting;
                            }
                            else
                            {
                                flowTaskInfoNext.finish_time =null;
                                flowTaskInfoNext.status = (int)FlowTaskStatus.Invalid;
                            }
                            flowTaskInfoNext.sort = sortIndex++;
                            flowTaskInfoNext.execute_type = (int)FlowTaskExecuteType.Waiting;
                            flowTaskInfos.Add(flowTaskInfoNext);
                        }
                    }
                }
            }
            return flowTaskInfos;
        }

        /// <summary>
        /// 流程步骤-退回操作
        /// </summary>
        /// <param name="taskId"></param>
        /// <param name="comments"></param>
        /// <returns></returns>
        public ResultJsonInfo<bool> ReturnFlow(string taskId, string comments) {

            var resultInfo = new ResultJsonInfo<bool>();
            //修改当前任务的信息
            var taskInfo = new FlowTaskInfoEntity();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                con.Transaction(tran =>
                {
                    //当前任务的信息
                    taskInfo = tran.QuerySet<FlowTaskInfoEntity>().Where(p => p.id.Equals(taskId)).Get();
                    taskInfo.comments = comments;
                    taskInfo.finish_time = DateTime.Now;
                    taskInfo.status = (int)FlowTaskStatus.Completed;
                    taskInfo.execute_type = (int)FlowTaskExecuteType.Returned;
                    tran.CommandSet<FlowTaskInfoEntity>().Update(taskInfo);
               });
           }

            //再来操作其余逻辑
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                con.Transaction(tran =>
                {

                    //该实例对应的所有任务
                    int isReturned = (int)FlowTaskExecuteType.Returned;
                    var allTasks = tran.QuerySet<FlowTaskInfoEntity>().Where(p => p.instance_id.Equals(taskInfo.instance_id)&&p.execute_type!=isReturned).ToList();
                    //该流程对应的所有步骤
                    var allSteps = tran.QuerySet<FlowStepInfoEntity>().Where(p => p.flow_id.Equals(taskInfo.flow_id)).ToList();
                    //该流程对应的所有连线
                    var allStepIds = allSteps.Select(p => p.id).ToArray();
                    //所有步骤连线
                    var allLines = tran.QuerySet<FlowLineInfoEntity>().Where(p => p.from.In(allStepIds) || p.to.In(allStepIds)).ToList();

                    //当前步骤
                    var nowStep = allSteps.Find(p => p.id.Equals(taskInfo.step_id));
                    //获取第一步Id
                    var startStep = allSteps.Find(p => p.parent_id == "");
                    //获取退回步骤的ID
                    List<string> steps = new List<string>();
                    //退回类型100退回上一步 110退回第一步 120退回指定步骤
                    switch (nowStep.return_type)
                    {
                        //退回上一步
                        case (int)FlowReturnType.BackLastStep:
                            steps = allLines.Where(p => p.to.Equals(nowStep.id)).Select(p => p.from).ToList();
                            break;
                        //退回第一步
                        case (int)FlowReturnType.BackFirstStep:
                            steps.Add(startStep.id);
                            break;
                        //退回指定步骤
                        case (int)FlowReturnType.BackSpecifiedStep:
                            steps.Add(nowStep.return_step);
                            break;
                        default:
                            break;
                    }
                    //退回步骤的任务
                    var stepIds = steps.ToArray();
                    var sameStepTaskInfos = allTasks.Where(p => stepIds.Contains(p.step_id)).ToList();
                    //修改退回的任务信息
                    foreach (var item in sameStepTaskInfos)
                    {
                        item.execute_type= (int)FlowTaskExecuteType.Waiting;
                        item.status = (int)FlowTaskStatus.Waiting;
                    }
                    tran.CommandSet<FlowTaskInfoEntity>().Update(sameStepTaskInfos);

                    //找出退回任务后面的所有任务，删除掉
                    var removeStepIds = GetReturnStepIds(allLines,steps);
                    if (removeStepIds.Count>0)
                    {
                        var removeStepIdArrs = removeStepIds.ToArray();
                        var invalidTasks = allTasks.Where(p => removeStepIdArrs.Contains(p.step_id)).Select(p => p.id).ToArray();
                        if (invalidTasks.Length > 0)
                        {
                            tran.CommandSet<FlowTaskInfoEntity>().Where(p => p.id.In(invalidTasks)).Delete();
                        }
                    }

                    //是否在起始步骤
                    if (steps.Count==1&& steps.Contains(startStep.id))
                    {
                        resultInfo.Data = true;
                    }
                    else
                    {
                        resultInfo.Data = false;
                    }
                    resultInfo.Msg = "操作成功";
                    resultInfo.Code = ActionCodes.Success;
                });
            }

            return resultInfo;
        }

        /// <summary>
        /// 获取退回步骤以后的所有步骤ID
        /// </summary>
        /// <param name="allLines"></param>
        /// <param name="stepIds"></param>
        /// <returns></returns>
        private List<string> GetReturnStepIds(List<FlowLineInfoEntity> allLines, List<string> stepIds) {

            List<string> retults = new List<string>();

            var toIds = allLines.Where(p => stepIds.Contains(p.from)).Select(p => p.to).ToList();
            if (toIds.Count>0)
            {
                retults.AddRange(toIds);

                retults.AddRange(GetReturnStepIds(allLines, toIds));
            }

            return retults;
        }

        /// <summary>
        /// 流程步骤-完成操作
        /// </summary>
        /// <param name="taskId"></param>
        /// <param name="comments"></param>
        /// <returns></returns>
        public ResultJsonInfo<bool> FinishFlow(string taskId, string comments)
        {
            var resultInfo = new ResultJsonInfo<bool>();
            //当前任务的信息
            var taskInfo = new FlowTaskInfoEntity();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                //当前任务的信息
                taskInfo = con.QuerySet<FlowTaskInfoEntity>().Where(p => p.id.Equals(taskId)).Get();
                taskInfo.comments = comments;
                taskInfo.finish_time = DateTime.Now;
                taskInfo.status = (int)FlowTaskStatus.Completed;
                taskInfo.execute_type = (int)FlowTaskExecuteType.Completed;
                con.CommandSet<FlowTaskInfoEntity>().Update(taskInfo);

                //该实例对应的所有任务
                int isReturned = (int)FlowTaskExecuteType.Returned;
                var allTasks = con.QuerySet<FlowTaskInfoEntity>().Where(p => p.instance_id.Equals(taskInfo.instance_id)&&p.execute_type!= isReturned).ToList();
                //该流程对应的所有步骤
                var allSteps = con.QuerySet<FlowStepInfoEntity>().Where(p => p.flow_id.Equals(taskInfo.flow_id)).ToList();
                //当前步骤
                var nowStep = allSteps.Find(p => p.id.Equals(taskInfo.step_id));
                //当前任务【同一步骤的】任务的信息
                var sameStepTaskInfos = allTasks.Where(p => p.instance_id.Equals(taskInfo.instance_id) && p.step_id.Equals(taskInfo.step_id)).ToList();
                var goNext = JudgmentStepCanBeNext(nowStep, sameStepTaskInfos);

                #region 判断当前步骤任务能否进入下一步,如果可以，先把状态改了
                if (goNext)
                {
                    foreach (var item in sameStepTaskInfos)
                    {
                        item.finish_time = DateTime.Now;
                        item.status = (int)FlowTaskStatus.Completed;
                        item.execute_type = (int)FlowTaskExecuteType.Completed;
                    }
                    con.CommandSet<FlowTaskInfoEntity>().Update(sameStepTaskInfos);
                }
                #endregion

                resultInfo.Msg = "操作成功";
                resultInfo.Code = ActionCodes.Success;
                if (goNext)
                {
                    resultInfo.Data = true;
                }
                else
                {
                    resultInfo.Data = false;
                }
            }
            return resultInfo;
        }

        #endregion

        #endregion
    }
}
